#include "SerialPort.h"
#include <QDebug>

/**
 * @brief 构造函数
 * @param parent 父对象指针
 */
SerialPort::SerialPort(QObject *parent) : CommunicationInterface(parent), m_serialPort(new QSerialPort(this)) {
    m_currentStatus = "disconnected";
}

/**
 * @brief 初始化串口
 * @param portName 串口名称（如"COM1"）
 * @param baudRate 波特率（默认9600）
 * @return 初始化成功返回true，失败返回false
 */
bool SerialPort::initialize(const QVariantMap &params) {
        QString portName = params.value("portName").toString();
        int baudRate = params.value("baudRate").toInt();
    if (m_serialPort->isOpen()) return false;

    m_serialPort->setPortName(portName);
    m_serialPort->setBaudRate(baudRate);
    m_serialPort->setDataBits(QSerialPort::Data8);
    m_serialPort->setParity(QSerialPort::NoParity);
    m_serialPort->setStopBits(QSerialPort::OneStop);
    m_serialPort->setFlowControl(QSerialPort::NoFlowControl);

    if (m_serialPort->open(QIODevice::ReadWrite)) {
        m_currentStatus = "connected";
        emit statusChanged(m_currentStatus);
        qDebug() << "Serial port " << portName << " initialized with baud rate " << baudRate;
        return true;
    } else {
        m_currentStatus = "init_failed";
        emit statusChanged(m_currentStatus);
        qWarning() << "Failed to open serial port: " << m_serialPort->errorString();
        return false;
    }
}

/**
 * @brief 反初始化并关闭串口
 */
void SerialPort::uninitialize() {
    if (m_serialPort->isOpen()) {
        m_serialPort->close();
        m_currentStatus = "disconnected";
        emit statusChanged(m_currentStatus);
        qDebug() << "Serial port closed.";
    }
}

/**
 * @brief 发送数据到串口
 * @param data 待发送的字节数据
 * @return 发送成功返回true，失败返回false
 */
bool SerialPort::sendData(const QByteArray &data) {
    if (!m_serialPort->isOpen()) {
        qWarning() << "Cannot send data: serial port is not open.";
        return false;
    }
    qint64 bytesWritten = m_serialPort->write(data);
    if (bytesWritten == data.size()) {
        qDebug() << "Sent " << bytesWritten << " bytes to serial port.";
        return true;
    } else {
        qWarning() << "Failed to send data: " << m_serialPort->errorString();
        return false;
    }
}

/**
 * @brief 获取通信类型
 * @return 字符串"SerialPort"
 */
QString SerialPort::type() const {
    return "SerialPort";
}

/**
 * @brief 获取当前状态
 * @return 状态描述字符串（如"connected"/"disconnected"）
 */
QString SerialPort::status() const {
    return m_currentStatus;
}